package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.SectionUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.SectionUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.dao.SectionUploadDao;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.entity.tbl_section;
import io.renren.modules.basedata.service.SectionUploadService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;


/**
 * @author djz
 * @version 上传收费路段信息
 */
@Service
public class SectionUploadServiceImpl implements SectionUploadService {

	private static final Logger log = Logger.getLogger(SectionUploadServiceImpl.class);


	@Autowired
	SectionUploadDao sectionUploadDao;
	@Autowired
	OperlogDao operlogDao;
	@Override
	public String sectionUpload() throws Exception {
		log.info("开始获取收费路段信息！");
		int operResult = 0;
		List<tbl_section> list = null;
		tbl_section section = null;
		tbl_Operlog operlog = new tbl_Operlog();
		list = getSectionList();//获取收费路段信息
		if(list!=null&&list.size()>0){
			
			for(int i=0;i<list.size();i++){
				section = list.get(i);
				DecimalFormat df = new DecimalFormat("######0.000000");
				Double sLat = section.getStartLat();
				Double sLng = section.getStartLng();
				Double eLat = section.getEndLat();
				Double eLng = section.getEndLng();
				String startLat = null;
				String startLng = null;
				String endLat = null;
				String endLng = null;
				if(section.getStartLat()!=null){
					startLat = df.format(sLat);
				}
				if(section.getStartLng()!=null){
					startLng = df.format(sLng);
				}
				if(section.getEndLat()!=null){
					endLat = df.format(eLat);
				}
				if(section.getEndLng()!=null){
					endLng = df.format(eLng);
				}
				
				//收费路段信息上传及变更接口
				SectionUploadRequest request = new SectionUploadRequest();
				request.setId(section.getId());
				request.setName(section.getName());
				request.setType(section.getType());
				request.setLength(section.getLength());
				request.setStartStakeNum(section.getStartStackNum());
//				request.setStartLat(String.valueOf(section.getStartLat()));
//				request.setStartLng(String.valueOf(section.getStartLng()));
//				request.setEndLat(String.valueOf(section.getEndLat()));
//				request.setEndLng(String.valueOf(section.getEndLng()));
				request.setStartLat(startLat);
				request.setStartLng(startLng);
				request.setEndLat(endLat);
				request.setEndLng(endLng);
				request.setEndStakeNum(section.getEndStackNum());
				request.setTax(section.getTax());
				request.setTaxRate(section.getTaxRate());
				request.setSectionOwnerId(section.getSectionOwnerId());
				request.setChargeType(section.getChargeType());
				request.setTollRoads(section.getTollRoads());
				request.setBuiltTime(DateUtil.formatDate(section.getBuiltTime()));
				request.setStartTime(DateUtil.formatDate(section.getStartTime()));
				request.setEndTime(DateUtil.formatDate(section.getEndTime()));
				request.setOperation(section.getFlag());
				//获取发送文件名
				String fileName = ETCCommHelper.getFileName(request,"65");
				//生成就json文件
//				CreateFileUtil.createJsonFile(request.toJsonStr(), "",fileName);
				
				try{
					//指定响应的协议模型,调用upload发送数据
					SectionUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request, SectionUploadResponse.class);
					log.info("上传收费路段信息成功,服务器返回:"+response.toJson());
					if(response!=null&&response.getInfo().equals("成功！")){

						//更新上传标志

						if(sectionUploadDao.updateSection(section.getId())==1){
							log.info("更新收费路段信息表上传标志成功!");
							operResult = 1;
							operlog = getOperlog(25,1,section.getId(),fileName ,operResult, response.getInfo(),"上传成功,更新成功");
						}else{
							log.info("更新收费路段信息表上传标志失败!");
							operlog = getOperlog(25,1,section.getId(),fileName ,operResult, response.getInfo(),"上传成功,更新失败");
							operlogDao.insertlog(operlog);
							//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
						}
//						sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					}else{
						log.info("上传收费公路信息失败!失败原因:"+response.getInfo());
						sectionUploadDao.updateSectionError(section.getId());
						//sqlMapClient.update("tollBaseInfo_ORACLE.updateSectionError",section.getId());
						
						//getOperlog（操作类型,传输类型,发送文件名,接收文件名,操作结果,部中心返回结果,说明）
						operlog = getOperlog(25,1 ,section.getId(),fileName ,0,response.getInfo(), response.toJson());
						operlogDao.insertlog(operlog);
						//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					}
				}catch(IOException e){
					log.error("上传收费公路信息失败！错误信息:",e);
					
//					sqlMapClient.update("tollBaseInfo_ORACLE.updateSectionError",section.getId());
					
					operlog = getOperlog(25, 1, section.getId(), fileName, 0,"IO异常", "出现IO异常,数据上传失败:"+e.getMessage());
					operlogDao.insertlog(operlog);
					//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					e.printStackTrace();
					continue;
				}catch (ApiRequestException apie) {
					log.error("上传收费公路信息失败！错误信息:",apie);
					
					if(apie.getErrCode()>=700&&apie.getErrCode()<=800){
						if(apie.getErrCode()==707){
							sectionUploadDao.updateSection(section.getId());
							//sqlMapClient.update("tollBaseInfo_ORACLE.updateSection",section.getId());
						}else{
							sectionUploadDao.updateSectionError(section.getId());
							//sqlMapClient.update("tollBaseInfo_ORACLE.updateSectionError",section.getId());
						}
					}
					
					operlog = getOperlog(25, 1, section.getId(), fileName, 0,String.valueOf(apie.getErrCode()), "出现Apie异常,数据上传失败:"+apie.getMessage());
					operlogDao.insertlog(operlog);
					//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					apie.printStackTrace();
					continue;
				}
			}
				return "上传收费路段信息结束！";
		}else{
			return "无收费路段信息,上传结束...";
		}
	}
	
	//获取收费路段信息
	@SuppressWarnings("unchecked")
	public List<tbl_section> getSectionList() throws IOException{
		List<tbl_section> list;
		try{
			list = sectionUploadDao.getSectionList();
			//list = sqlMapClient.queryForList("tollBaseInfo_ORACLE.getSectionList");
		}catch(Exception e){
			e.printStackTrace();
			log.error("获取收费路段信息失败！错误信息:",e);
			throw new IOException("获取收费路段信息失败:"+e.getMessage());
		}
		return list;
	}
	
	//获取operlog信息
	public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
		tbl_Operlog operlog = new tbl_Operlog();
		operlog.setWastesn(new GUID().toString());
		operlog.setOperTime(new Date());
		operlog.setOpertype(operType);
		operlog.setSoftType(softType);
		operlog.setSendFileName(sendFileName);
		operlog.setReFileName(reFileName);
		operlog.setOperResult(operResult);
		operlog.setReResult(reResult);
		operlog.setContent(content);
		return operlog;
	}
	
}
